package com.lovi.dao;

import com.lovi.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BaseDao<T> {
    /**
     * dml语句
     */
    public int update(String sql, Object... params){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            QueryRunner qr = new QueryRunner();
            int affectedRow = qr.update(connection, sql, params );
            System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表");
            JDBCUtilsByDruid.close(null,null,connection);
            return affectedRow;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
    /**
     * 获取多行集合
     */
    public  List<T> list(Class<T> classT, String sql, Object... params){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            QueryRunner qr = new QueryRunner();
            //返回结果是多行的情况
            List<T> list =
                    qr.query(connection, sql, new BeanListHandler<T>(classT), params);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }
    /**
     * 获取单行
     */
    public  <T> T  getOneById(Class<T> classT, String sql, Object... params){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            QueryRunner qr = new QueryRunner();
            //返回结果是多行的情况
            T t = qr.query(connection, sql, new BeanHandler<T>(classT), params);
            return t;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }
    /**
     * 获取单行单列
     */
    public  <T> T  getOneFiledById(Class<T> classT, String sql, Object... params){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            QueryRunner qr = new QueryRunner();
            //返回结果是多行的情况
            T t = qr.query(connection, sql, new ScalarHandler<>(), params);
            return t;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.close(null,null,connection);
        }
    }



}
